#include <thread>

#include "TaskInstallapp.h"
#include "ServiceConnection.h"
#include "App.h"
#include "AdbHelper.h"

namespace Gnodroid {

    TaskInstallapp::TaskInstallapp(std::string apkPath) :
        Task(TaskProgressType::NONE)
    {
        m_adbPath = apkPath;
    }

    void
    TaskInstallapp::start()
    {
        updateState(TaskState::RUNNING);
        updateLabel(std::string("Install apk: ") + m_adbPath);
        updateMessage("Installing");

        ServiceConnection* serviceConnection = static_cast<ServiceConnection*>(App::getService(SERVICE_CONNECTION));

        if (!serviceConnection->isConnecting()) {
            updateMessage("Not connected");
            updateState(TaskState::ERROR);
            return;
        }

        std::thread t(sigc::mem_fun(*this, &TaskInstallapp::__installAppThread), m_adbPath);
        t.detach();
        return;
    }

    void
    TaskInstallapp::__installAppThread(std::string apkPath)
    {

        ServiceConnection* serviceConnection = static_cast<ServiceConnection*>(App::getService(SERVICE_CONNECTION));

        if (!AdbHelper::installApp(serviceConnection->getAdbPath(),
                                  serviceConnection->getDeviceId(),
                                   apkPath)) {
            updateMessage("Install app failed");
            updateState(TaskState::ERROR);
            return;
        }

        updateMessage("Success");
        updateState(TaskState::FINNISHED);
        return;
    }



}
